package com.cyz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.admin.service.Admin_UserService;
import com.cyz.common.bean.Menu;
import com.cyz.common.dto.MenuDto;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.mapper.MenuMapper;
import com.cyz.admin.service.Admin_MenuService;
import com.cyz.common.mapper.RoleMenuMapper;
import com.cyz.common.mapper.UserMapper;
import com.cyz.common.mapper.UserRoleMapper;
import com.cyz.common.service.RoleMenuService;
import com.cyz.common.service.UserRoleService;
import com.cyz.common.utils.BeanCopyUtil;
import com.cyz.common.utils.R;
import com.cyz.common.utils.SecurityUtils;
import com.cyz.admin.vo.MenuVo;
import com.cyz.admin.vo.RoleMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 34928
* @description 针对表【menu(菜单权限表)】的数据库操作Service实现
* @createDate 2023-02-22 11:39:30
*/
@Service
@Transactional
public class AdminMenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements Admin_MenuService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private Admin_UserService admin_userService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public R queryMenus() {
        //查询数据
        List<Menu> list = menuMapper.queryMenus();
        //vo处理
        List<MenuVo> menuVos = BeanCopyUtil.copyBeanList(list, MenuVo.class);
        //错误判断
        if(menuVos.isEmpty()){
            return R.error(MyEnums.QUERY_FAIL);
        }
        return R.success(menuVos);
    }

    @Override
    public R addMenu(MenuDto menuDto) {
        Menu menu = BeanCopyUtil.copyBean(menuDto, Menu.class);

        boolean flag = menuMapper.addMenu(menu);
        if(flag){
            return admin_userService.getRouters();
        }
        return R.error(MyEnums.ADD_FAIL);
    }

    @Override
    public R updateMenu(MenuDto menuDto) {
        Menu menu = BeanCopyUtil.copyBean(menuDto, Menu.class);
        boolean flag = menuMapper.updateMenu(menu);
        if(flag){
            return admin_userService.getRouters();
        }
        return R.error(MyEnums.UPDATE_FAIL);
    }

    @Override
    public R deleteMenu(Integer id) {
        boolean flag = menuMapper.deleteMenu(id);
//        removeMenuChildren(id);
        if(flag){
            return admin_userService.getRouters();
        }
        return R.error(MyEnums.DELETE_FAIL);
    }

//    public void removeMenuChildren(Integer id){
//        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Menu::getParentId,id);
//        list(lambdaQueryWrapper).stream()
//                .map(Menu::getId)
//                .forEach(item -> {
//                    removeMenuChildren(item);
//                    removeById(item);
//                });
//    }

    @Override
    public List<String> queryMenusById(Integer userId) {
        return null;
    }

    @Override
    public List<MenuVo> getRouterMenuTreeByUserId(Integer userId) {
        List<Menu> menus = null;
        //如果用户为超级管理员,返回所有符合要求的路由
        if(SecurityUtils.IsAdmin()){
            //创建筛选器
            LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //菜单类别应为C，M
            lambdaQueryWrapper.in(Menu::getMenuType,MyEnums.MENU,MyEnums.DIRECTORY);
            //菜单应为未禁用的状态
            lambdaQueryWrapper.eq(Menu::getStatus,MyEnums.NORMAL_STATUS);
            //排序
            lambdaQueryWrapper.orderByAsc(Menu::getOrderNum);
            menus = list(lambdaQueryWrapper);
        }else{
            //根据userID 查询角色id
            List<Integer> roleIds = userRoleService.getRoleIdsByUserId(userId);
            //根据角色id 查询菜单id
            List<Integer> menuIds = roleMenuService.getMenuIdsByRoleIds(roleIds);
            //根据菜单id 查询权限
            Set<Menu> set = new HashSet<>();
            menuIds
                    .forEach(item -> {
                        set.add(getById(item));
                    });
            menus = new ArrayList<>(set);
        }
        //vo处理
        List<MenuVo> menuVos = BeanCopyUtil.copyBeanList(menus, MenuVo.class);
        //构建tree
        return buildMenuTree(menuVos,MyEnums.MENU_ROOT);
    }

    @Override
    public R queryMenuTrees() {
        List<Menu> menus = null;
        //如果用户为超级管理员,返回所有符合要求的路由
        if(SecurityUtils.IsAdmin()){
            //创建筛选器
            LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //菜单类别应为C，M
            lambdaQueryWrapper.in(Menu::getMenuType,MyEnums.MENU,MyEnums.DIRECTORY);
            //菜单应为未禁用的状态
            lambdaQueryWrapper.eq(Menu::getStatus,MyEnums.NORMAL_STATUS);
            //排序
            lambdaQueryWrapper.orderByAsc(Menu::getOrderNum);
            menus = list(lambdaQueryWrapper);
        }else{
            //根据userID 查询角色id
            List<Integer> roleIds = userRoleService.getRoleIdsByUserId(SecurityUtils.getUserId());
            //根据角色id 查询菜单id
            List<Integer> menuIds = roleMenuService.getMenuIdsByRoleIds(roleIds);
            //根据菜单id 查询权限
            Set<Menu> set = new HashSet<>();
            menuIds
                    .forEach(item -> {
                        set.add(getById(item));
                    });
            menus = new ArrayList<>(set);
        }
        //vo处理
        List<MenuVo> menuVos = BeanCopyUtil.copyBeanList(menus, MenuVo.class);
        //构建tree
        List<MenuVo> menuVos1 = buildMenuTree(menuVos, MyEnums.MENU_ROOT);

        List<RoleMenuVo> roleMenuVos = menuToRoleMenu(menuVos1);

        return R.success(roleMenuVos);
    }

    public List<RoleMenuVo> menuToRoleMenu(List<MenuVo> menuVos){
        List<RoleMenuVo> list = new ArrayList<>();
        menuVos.forEach(item ->{
            RoleMenuVo roleMenuVo = new RoleMenuVo();
            roleMenuVo.setValue(item.getId());
            roleMenuVo.setLabel(item.getMenuName());
            roleMenuVo.setChildren(menuToRoleMenu(item.getChildren()));
            list.add(roleMenuVo);
        });
        return list;
    }

    public List<MenuVo> buildMenuTree(List<MenuVo> menus,Integer parentId) {
//        List<MenuVo> collect = menus.stream()
//                .filter(item -> !Objects.equals(item.getParentId(), parentId))
//                .collect(Collectors.toList());
        List<MenuVo> collect = menus.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .map(item -> item.setChildren(getChildren(item, menus)))
                .collect(Collectors.toList());
        return collect;
    }

    private List<MenuVo> getChildren(MenuVo item,List<MenuVo> menus) {
//        if (menus.isEmpty()){
//            return null;
//        }
//        List<MenuVo> collect = menus.stream()
//                .filter(i -> !Objects.equals(i.getParentId(), i.getId()))
//                .collect(Collectors.toList());
//        menus.stream()
//                .filter(m -> m.getParentId().equals(item.getId()))
//                .forEach(m -> m.setChildren(getChildren(m,menus)));
//        return menus;
        List<MenuVo> collect = menus.stream()
                .filter(m -> m.getParentId().equals(item.getId()))
                .map(m -> m.setChildren(getChildren(m,menus)))
                .collect(Collectors.toList());
        return collect;
    }
}




